<template>

  <page-header-wrapper>
    <template #extra>
      <a-button type="primary" @click="toRoute('/goods/add')">
        创建商品
      </a-button>
    </template>
    <div class="table-page-search-wrapper">
      <a-card>
        <a-form layout="inline" style="margin-bottom: 5px;">
          <a-row :gutter="48">
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="商品名称">
                <a-input v-model="search.text" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="商品类型">
                <a-cascader :field-names="{ label: 'type', value: 'id', children: 'children' }" :options="typeTreeList"
                            change-on-select placeholder="Please select" @change="onGoodsTypeChange"/>
              </a-form-item>
            </a-col>
            <!--            <a-col :xl="6" :lg="8" :md="12" :xs="24">-->
            <!--              <a-form-item label="商品状态">-->
            <!--                <a-select :default-value="null" @change="handleUserState">-->
            <!--                  <a-select-option :value="null">-->
            <!--                    全部-->
            <!--                  </a-select-option>-->
            <!--                  <a-select-option :value="1">-->
            <!--                    使用中-->
            <!--                  </a-select-option>-->
            <!--                  <a-select-option :value="0">-->
            <!--                    已禁用-->
            <!--                  </a-select-option>-->
            <!--                </a-select>-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="每页条数">
                <a-select :default-value="10" @change="handlePageSize">
                  <a-select-option :value="value" v-for="value in pageSizeSelect" :key="value">
                    {{ value }}条/页
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-button type="primary" @click="handleTableChange">查询</a-button>
            </a-col>
          </a-row>
        </a-form>


        <a-table :pagination="pagination" bordered
                 :data-source="data" :loading="loading"
                 size="small" :columns="columns"
                 @change="handleTableChange"
                 :expandRowByClick="true"
        >
          <img slot="image" slot-scope="text,record" :src="text"
               style="width: 100px;height: 100px;object-fit: contain;">
          <div slot="status" slot-scope="text,record">
            <a-badge :color="Number(text)==1?'green':'red'"
                     :text="Number(text)==1?'售卖中':'停售中'"/>
          </div>
          <div slot="type" slot-scope="text,record">
            <span v-if="record.primaryTypeId!=null">
            {{ typeMap.get(record.primaryTypeId).type == null ? '未知分类' : typeMap.get(record.primaryTypeId).type }}
              <span v-if="record.secondaryTypeId!=null">
                {{
                  typeMap.get(record.secondaryTypeId) != null ? (' / ' + typeMap.get(record.secondaryTypeId).type) : null
                }}
                <span v-if="record.tertiaryTypeId!=null">
            {{ typeMap.get(record.tertiaryTypeId) != null ? (' / ' + typeMap.get(record.tertiaryTypeId).type) : null }}
                </span>
              </span>
            </span>
            <span v-else>
              未知分类
            </span>
          </div>
          <div slot="action" slot-scope="text,record">
            <div style="display: inline-block;margin-left: 10px">
              <a-button type="link" size="small" @click="toGoodsPage(record.id)">查看详情</a-button>
              <a-divider type="vertical" v-if="record.level!=1"/>
              <a-button type="link" size="small" @click="toAddToMainPageRecommendGoods(record.id)">添加到首页</a-button>
              <a-divider type="vertical" v-if="record.level!=1"/>
              <a-button type="link" size="small" @click="toDeleteGoodById(record.id)">删除</a-button>
            </div>
          </div>

          <div slot="expandedRowRender" slot-scope="record" style="margin: 0">
            <a-table bordered :pagination="false"
                     :data-source="record.goodsSpecifications" :loading="loading"
                     size="small" :columns="columns1">
              <div slot="specifications" slot-scope="specificationRecord">
                <div v-for="specification in specificationRecord.specification">
                  <span>{{ specification.key }}</span> / <span>{{ specification.value }}</span>
                </div>
              </div>
            </a-table>
          </div>


        </a-table>
      </a-card>
    </div>
  </page-header-wrapper>

</template>

<script>

import {getCommunity} from "@/api/community";
import {searchTypeAsTree} from "@/api/modules/TypeRequest";
import {deleteGoodById, searchGoodByPage} from "@/api/modules/GoodRequest";
import router from '@/router'
import {addRecommendById} from "@/api/modules/MainPageRequest";

const columns = [
  {
    "dataIndex": "name",
    key:'id',
    "title": "商品名称",
  },
  {
    "dataIndex": "mainImage",
    "title": "商品图片",
    key:'id',
    scopedSlots: {customRender: 'image'},
  },
  {
    "dataIndex": "producer",
    key:'id',
    "title": "生产商",
  },
  {
    "dataIndex": "type",
    key:'id',
    "title": "型号",
    customRender(text, record) {
      if (text != null) {
        return text
      } else {
        if (record == null || record.goodsSpecifications == null || record.goodsSpecifications.length <= 1) {
          return '暂无型号'
        }
        return '展开查看'
      }
    }
  },
  {
    "title": "商品分类",
    scopedSlots: {customRender: 'type'},
  },
  // {
  //   "title": "门牌号",
  //   customRender(text, e) {
  //     let str = '';
  //     if (e.tower == undefined && e.unit == undefined) return str
  //     str += (e.tower || '') + ' / ' + (e.unit || '')
  //     if (e.address != null)
  //       str += '/' + e.address
  //     return str
  //   }
  // },
  {
    "dataIndex": "status",
    "title": "商品状态",
    scopedSlots: {customRender: 'status'},
  },
  {
    "dataIndex": "price",
    key:'id',
    "title": "价格",
    customRender(text) {
      if (text != null) {
        return '$ ' + text
      } else {
        return '展开查看'
      }
    }
  },
  {
    "dataIndex": "stock",
    key:'id',
    "title": "库存",
    customRender(text) {
      if (text != null) {
        return text
      } else {
        return '展开查看'
      }
    }
  },
  {
    "title": "操作",
    scopedSlots: {customRender: 'action'},
  },

  // {
  //   "dataIndex": "isSpecial",
  //   "title": "是否为特殊用户",
  //   scopedSlots: {customRender: 'isSpecial'},
  // }
]

const columns1 = [
  {
    "title": "规格",
    scopedSlots: {customRender: 'specifications'},
  },
  {
    "dataIndex": "type",
    "title": "型号",
    customRender(text, record) {
      if (text != null) {
        return text
      } else {
        return '暂无型号'
      }
    }
  },
  {
    "dataIndex": "price",
    "title": "价格",
    customRender(text) {
      if (text != null) {
        return '$ ' + text
      } else {
        return 0
      }
    }
  },
  {
    "dataIndex": "stock",
    "title": "库存",
    customRender(text) {
      if (text != null) {
        return text
      } else {
        return 0
      }
    }
  },
  {
    "dataIndex": "maxNumber",
    "title": "单个订单最大购买量",
    customRender(text) {
      if (text != null) {
        return text
      } else {
        return '无限制'
      }
    }
  },
  {
    "dataIndex": "createAt",
    "title": "规格创建时间",
  },
  {
    "dataIndex": "updateAt",
    "title": "规格修改时间",
  },
]

export default {
  name: "GoodsList",
  data() {
    return {
      search: {
        id: '',
        name: '',
        producer: ''
      },
      typeTreeList: [],
      typeMap: new Map(),
      data: [],
      columns: columns,
      columns1,
      loading: true,
      pagination: {
        pageSize: "10",
        current: 1,
        total: 0
      },
      community: [
        {
          id: null,
          name: '全部'
        }
      ],
      pageSizeSelect: [
        '5', '10', '20', '50', '100'
      ],
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      try {
        let data=JSON.parse(decodeURIComponent(this.$route.query.info))
        this.search = Object.assign({}, this.search, data.search)
        this.pagination = Object.assign({}, this.pagination, data.pagination)
      }catch (e){

      }

      await this.toSearchType()
      await this.handleTableChange();
    },
    async toRoute(path) {
      router.push({
        path
      })
    },
    async toAddToMainPageRecommendGoods(id) {
      await addRecommendById(id).then(res => {
        this.$notification.success({
          message: '添加成功'
        })
      })
    },
    async toSearchType() {
      let _this = this;
      await searchTypeAsTree().then((res) => {
        if (res.status === 200) {
          _this.typeTreeList = [
            {id: null, type: '全部'}, ...res.data
          ];

          let arr = [...res.data]

          for (let i = 0; i < arr.length; i++) {
            _this.typeMap.set(arr[i].id, arr[i]);
            if (arr[i].children != null && arr[i].children.length > 0) {
              arr.push(...arr[i].children)
            }
          }

        } else {
          _this.$notification.warning({
            message: res.message
          })
        }
      }).catch((res) => {
        _this.$notification.warning({
          message: res.message
        })
      })
    },

    async handlePageSize(value) {
      this.pagination.pageSize = value.toString();
      await this.handleTableChange();
    },
    async handleTableChange(pagination) {
      this.loading = true;
      if (pagination != null) this.pagination.current = pagination.current
      await this.searchGoods();
      this.loading = false;
    },

    onCommunityChange(value) {
      this.search.communityId = value[0];
    },
    handleIsSpecialChange(e1) {
      this.search.isSpecial = e1
    },
    handleUserState(value) {
      this.search.status = value
    },
    changeSpecial(e) {
      let _this = this;
      console.log(e)
      updateUser({
        id: e.id,
        isSpecial: e.isSpecial == 1 ? 2 : 1
      }).then(() => {
        _this.handleTableChange();
      })
    },
    async searchGoods() {
      let _this = this;
      if (this.pagination.current == null) this.pagination.current = 1;
      searchGoodByPage({
        current: this.pagination.current,
        size: this.pagination.pageSize,
        typeId: this.search.type,
        'text': [null, ''].indexOf(this.search.text) === -1 ? this.search.text : null,
      }).then((res) => {
        if (res.status === 200) {
          for (let i = 0; i < res.data.records.length; i++) {
            if(res.data.records[i].goodsSpecifications==null)continue;
            for (let j = 0; j < res.data.records[i].goodsSpecifications.length; j++) {
              res.data.records[i].goodsSpecifications[j].specification = JSON.parse(res.data.records[i].goodsSpecifications[j].specification)
            }
          }
          _this.data = res.data.records
          _this.pagination.total = res.data.total
          _this.pagination.current = res.data.current
          _this.pagination.pageSize = res.data.size.toString()
        } else {
          _this.$notification.warning({
            message: res.message
          })
        }
        let newRoute=Object.assign({}, this.$route, {
          query: {
            info:encodeURIComponent(JSON.stringify({
              search: this.search,
              pagination: this.pagination,
            }))
          }
        })
        delete newRoute.path;
        delete newRoute.matched;
        delete newRoute.fullPath;
        delete newRoute.hash;
        delete newRoute.meta;
        console.log(newRoute)
        this.$router.push(newRoute)
      });
    },
    onGoodsTypeChange(value, selectedOptions) {
      console.log(value)
      if (value == null || value.length == 0) this.search.type = null
      else this.search.type = value[value.length - 1]
    },
    async toDeleteGoodById(id) {
      let _this = this;
      this.$confirm({
        title: '确定删除该商品？',
        async onOk() {
          _this.loading = true;
          await deleteGoodById(id).then(() => {
            _this.searchGoods();
          })
          _this.loading = false;
        }
      })
    },
    toGoodsPage(id) {
      router.push({
        path: '/goods/goodInfo/' + id,
      })
    }
  }
}
</script>

<style scoped>

</style>